﻿using System;
using System.Globalization;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
public partial class AspNetUpload : System.Web.UI.Page
{
    /// <summary>
    /// 允许上传大小(单位KB)
    /// </summary>
    int UploadImageSize = Convert.ToInt32(ConfigurationManager.AppSettings["EditImgupSize"]);
    /// <summary>
    /// 允许上传文件类型(带[.]的扩展名)
    /// </summary>
    string UploadImageExts = ConfigurationManager.AppSettings["EditImgupType"];
    /// <summary>
    /// 上传目录(绝对虚拟目录,以[/]开头,以[/]结尾)
    /// </summary>
    string UploadImageDir = ConfigurationManager.AppSettings["EditImgupload"];  


    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            doUploadImagePost();
        }
    }

    protected void doUploadImagePost()
    {
        HttpPostedFile PostedFile = Request.Files["imgFile"];
        if (PostedFile == null)
        {
            ReturnFalse("上传文件元素不存在!");
            return;
        }
        long FileLength = PostedFile.ContentLength;
        string FileName = PostedFile.FileName;
        //判断文件是否大于0字节或文件名是否为空
        if (FileLength <= 0 || string.IsNullOrEmpty(FileName))
        {
            ReturnFalse("未选择需要上传文件!");
            return;
        }
        if (FileName.IndexOf(".") < 0)
        {
            ReturnFalse("上传文件为未知文件!");
            return;
        }
        string FileExtension = FileName.Substring(FileName.LastIndexOf(".")).ToLower();

        //判断是否是允许上传的文件类型
        if (TrueFileExtension(FileExtension) == false)
        {
            ReturnFalse("不允许上传的文件类型,只允许上传以下类型文件:\\n[" + UploadImageExts.Replace("|", ", ") + "]!");
            return;
        }
        long MaxFileLength = UploadImageSize * 1024;
        //判断是否在允许上传的大小之内
        if (FileLength > MaxFileLength)
        {
            ReturnFalse("上传文件大小超过最大限制(" + MaxFileLength.ToString() + "K)!");
            return;
        }


        string NewFilePath = UploadImageDir + GetSaveFolder() + GetNewFileName() + FileExtension;
        //如要保留注原文件名,请注消或删除上面一行,取消下面一行注释
        //string NewFilePath = UploadImageDir + GetSaveFolder() + System.IO.Path.GetFileName(FileName);
        //string FileSaveDir = HttpContext.Current.Server.MapPath(NewFilePath);
        string FileSaveDir = NewFilePath;
        try
        {
            //先判断目录是否存在,不存在创建
            if (System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(FileSaveDir)) == false)
            {
                System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(FileSaveDir));
            }
            PostedFile.SaveAs(FileSaveDir);
            ReturnTrue(NewFilePath);
        }
        catch
        {
            //如果出现错误,可能上传目录无写入权限,需检查
            ReturnFalse("上传文件保存失败,请重试!\\n如多次重试无效,请与本网管理员联系!");
            return;
        }

        PostedFile = null;
    }
    /// <summary>
    /// 根据时间得到存放目录(以[/]结尾)
    /// </summary>
    /// <returns>yyyy-MM/</returns>
    public string GetSaveFolder()
    {
        return DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "/";
        //+DateTime.Now.Day.ToString() + "/";
    }
    /// <summary>
    /// 根据时间和随机数得到新文件名(不带扩展名)
    /// </summary>
    /// <returns>yyyyMMddHHmmssff12345</returns>
    public string GetNewFileName()
    {
        return DateTime.Now.ToString("yyyyMMddHHmmssff") + new Random().Next(10000, 99999).ToString();
    }
    /// <summary>
    /// 判断是否是允许上传的文件类型
    /// </summary>
    /// <returns>True/False</returns>
    public bool TrueFileExtension(string FileExt)
    {
        string[] TempExtensions = UploadImageExts.ToLower().Split('|');
        for (int i = 0; i < TempExtensions.Length; i++)
        {
            if (TempExtensions[i] == FileExt) return true;
        }
        return false;
    }

    protected void ReturnTrue(string imgUrl)
    {
        OuterHTML("parent.KE.plugin['image'].insert('" + Request.Form["id"] + "','" + imgUrl + "','" + Request.Form["imgTitle"] + "','" + Request.Form["imgWidth"] + "','" + Request.Form["imgHeight"] + "','" + Request.Form["imgBorder"] + "');");
    }

    protected void ReturnFalse(string Msg)
    {
        OuterHTML("alert('" + Msg + "');history.back();");
    }

    protected void OuterHTML(string JScript)
    {
        Response.Write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
        Response.Write("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
        Response.Write("<head><title>error</title><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" /></head>");
        Response.Write("<body><script type=\"text/javascript\">" + JScript + "</script></body>");
        Response.Write("</html>");
    }


}